package com.yaofeng.mybatis.util;

import com.yaofeng.mybatis.modules.sys.vo.SelectTreeVo;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建树形结构的类SelectTreeBuildUtil。方法getRootNode获取所有根节点，
 * * 方法builTree将根节点汇总创建树形结构，buildChilTree为节点建立次级树并拼接上当前树，
 * * 递归调用buildChilTree不断为当前树开枝散叶直至找不到新的子树。完成递归，获取树形结构。
 * Created by yaofeng on 2019/11/4.
 */
public class SelectTreeBuildUtil {


    private List<SelectTreeVo> treeList;

    /**
     * 构建树形菜单
     *
     * @param treeList
     */
    public SelectTreeBuildUtil(List<SelectTreeVo> treeList) {
        this.treeList = treeList;

    }

    /**
     * 构建树形
     *
     * @return
     */
    public List<SelectTreeVo> builTree() {
        List<SelectTreeVo> treeMenus = new ArrayList<>();
        for (SelectTreeVo menuNode : getRootNode()) {
            menuNode = buildChilrenTree(menuNode);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }


    /**
     * 获取所有根节点 parentId =0
     *
     * @return
     */
    private List<SelectTreeVo> getRootNode() {
        List<SelectTreeVo> rootMenuLists = new ArrayList<>();
        for (SelectTreeVo menuNode : treeList) {
            if (menuNode.getParentId().equals(0L)) {
                rootMenuLists.add(menuNode);
            }
        }
        if(rootMenuLists.isEmpty()){
            rootMenuLists=treeList;
        }
        return rootMenuLists;
    }

    /**
     * 递归，建立子树形结构
     *
     * @param parentVo 父节点
     * @return
     */
    private SelectTreeVo buildChilrenTree(SelectTreeVo parentVo) {
        List<SelectTreeVo> childVo = new ArrayList<>();
        for (SelectTreeVo menuNode : treeList) {
            if (menuNode.getParentId().equals(parentVo.getId()) ) {
                childVo.add(buildChilrenTree(menuNode));
            }
        }
        parentVo.setChildren(childVo);
        return parentVo;
    }


}
